package cn.darxs.noquestion.controller;

import cn.darxs.noquestion.common.Response;
import cn.darxs.noquestion.entity.*;
import cn.darxs.noquestion.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static cn.darxs.noquestion.common.ResponseStateCode.NO_LOGIN;
import static cn.darxs.noquestion.common.ResponseStateCode.OPERATION_SUCCEED;

/**
 * @program: no-question
 * @description: 问卷控制器
 * @author: leaven
 * @create: 2022-10-30 16:15
 **/
@Slf4j
@RestController
@RequestMapping("/questionnaire")
public class QuestionnaireController {
        @Autowired
        QuestionnaireService questionnaireService;

        @Autowired
        UserService userService;

        @Autowired
        QuestionRelationService questionRelationService;

        @Autowired
        QuestionService questionService;

        @Autowired
        QuestionOptionService questionOptionService;


        /**
         * 问卷进行标记删除，并且从网页端获取session
         *
         * @param id
         * @return
         */
        @DeleteMapping("/{id}")
        public Response updateDelete(@PathVariable Long id, HttpServletRequest request) {
            Response httpResponseEntity = new Response();
            //从前端直接得到内容
            Long userID = (Long) request.getSession().getAttribute("userId");

            //从数据库中得到id与前端获取id比较，得到one结果
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getId, userID);
            User one = userService.getOne(queryWrapper);
            if (one != null) {
                //目的是将删除时间字段填充
                Questionnaire byId = questionnaireService.getById(id);
                byId.setDeleteTime(LocalDateTime.now());
                questionnaireService.saveOrUpdate(byId);
                httpResponseEntity.setCode(OPERATION_SUCCEED); //回来统一这些code 和 Message
                httpResponseEntity.setMessage("创建成功");
                httpResponseEntity.setData("1");
            } else {
                httpResponseEntity.setCode(NO_LOGIN); //回来统一这些code 和 Message
                httpResponseEntity.setMessage("创建失败");
                httpResponseEntity.setData("2");
            }
            return httpResponseEntity;
        }

        /*
         * 添加问卷
         * */
        @PostMapping()
        public Response createQuestionaire(HttpServletRequest request, @RequestBody JsonQuestion params) {
            Response response = new Response();
            Long userId =(Long) request.getSession().getAttribute("userId");

            Questionnaire questionnaire = new Questionnaire();
            String questionNaireName = params.questionNaireName;
            log.info("{}", params.questionNaireName);
            log.info("{}", params.questionIds);
            List<String> questionIds = params.questionIds;

            questionnaire.setCreateUserId(userId);
            questionnaire.setName(questionNaireName);
            questionnaireService.save(questionnaire);

            QuestionRelation questionRelation;
            for (String questionId : questionIds) {
                questionRelation = new QuestionRelation();
                questionRelation.setQuestionId(Long.parseLong(questionId));
                questionRelation.setQuestionnaireId(questionnaire.getId());
                questionRelationService.save(questionRelation);
            }

            response.setCode(OPERATION_SUCCEED);
            return response;
        }

        /*
         * 获取所有问题
         * */
        @GetMapping()
        public Response getAllQuestions() {
            Response response = new Response();
            List<Question> questions = questionService.list();
            response.setData(questions);
            response.setCode(OPERATION_SUCCEED);
            return response;
        }


        @Data
        static class JsonQuestion implements Serializable {
            List<String> questionIds;
            String questionNaireName;
        }

        @Data
        static class ResponseData implements Serializable{
            String questionNaireName;
            List<QuestionNaireResponse> questions = new ArrayList<>();
        }

        @Data
        class QuestionNaireResponse implements Serializable{
            String questionId;
            List<String> options;
        }



        @GetMapping("/{questionNaireId}")
        public Response getQuestionnaireById(@PathVariable long questionNaireId){
            Response response = new Response();
            ResponseData responseData = new ResponseData();
            Questionnaire questionnaire = questionnaireService.getById(questionNaireId);
            responseData.setQuestionNaireName(questionnaire.getName());
            LambdaQueryWrapper<QuestionRelation> questionRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
            questionRelationLambdaQueryWrapper.eq(QuestionRelation::getQuestionnaireId,questionNaireId);
            List<QuestionRelation> questionRelations = questionRelationService.list(questionRelationLambdaQueryWrapper);
            List<Long> questionIds = new ArrayList<>();
            for(QuestionRelation questionRelation : questionRelations){
                questionIds.add(questionRelation.getQuestionId());
            }
            List<QuestionNaireResponse> questionNaireResponses = new ArrayList<>();
            QuestionNaireResponse questionNaireResponse ;
            for(long questionId : questionIds){
                LambdaQueryWrapper<QuestionOption> questionOptionLambdaQueryWrapper = new LambdaQueryWrapper<>();
                questionOptionLambdaQueryWrapper.eq(QuestionOption::getQuestionId,questionId);
                List<QuestionOption> questionOptions = questionOptionService.list(questionOptionLambdaQueryWrapper);
                questionNaireResponse = new QuestionNaireResponse();
                List<String> option = new ArrayList<>();
                for(QuestionOption questionOption : questionOptions){
                    log.info(questionOption.getDescription());
                    option.add(questionOption.getDescription());
                }
                questionNaireResponse.setOptions(option);
                questionNaireResponse.setQuestionId(questionId+"");
                questionNaireResponses.add(questionNaireResponse);
            }
            responseData.setQuestions(questionNaireResponses);
            response.setData(responseData);
            response.setCode(OPERATION_SUCCEED);
            return response;
        }


}

